#!/bin/bash
# 日志清理脚本

LOG_DIR="/opt/erp-mock/logs"
RETENTION_DAYS=30
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

echo "========================================"
echo "日志清理脚本"
echo "开始时间: $TIMESTAMP"
echo "========================================"

if [ ! -d "$LOG_DIR" ]; then
    echo "✗ 日志目录不存在: $LOG_DIR"
    exit 1
fi

# 统计清理前的日志文件数量和大小
BEFORE_COUNT=$(find $LOG_DIR -name "*.log.*" -type f | wc -l)
BEFORE_SIZE=$(du -sh $LOG_DIR | cut -f1)

echo "清理前: $BEFORE_COUNT 个归档日志, 总大小: $BEFORE_SIZE"

# 删除超过保留天数的归档日志
echo "正在删除 ${RETENTION_DAYS} 天前的归档日志..."
DELETED_FILES=$(find $LOG_DIR -name "*.log.*" -type f -mtime +$RETENTION_DAYS -print -delete)
DELETED_COUNT=$(echo "$DELETED_FILES" | grep -c "^" 2>/dev/null || echo 0)

# 统计清理后的日志文件数量和大小
AFTER_COUNT=$(find $LOG_DIR -name "*.log.*" -type f | wc -l)
AFTER_SIZE=$(du -sh $LOG_DIR | cut -f1)

echo "清理后: $AFTER_COUNT 个归档日志, 总大小: $AFTER_SIZE"
echo "✓ 已删除 $DELETED_COUNT 个过期日志文件"

# 压缩大于100MB的当前日志文件
echo ""
echo "检查大日志文件..."
find $LOG_DIR -name "*.log" -type f -size +100M | while read logfile; do
    echo "压缩大日志文件: $logfile"
    gzip "$logfile"
    mv "$logfile.gz" "$logfile.$(date +%Y%m%d_%H%M%S).gz"
done

echo ""
echo "日志清理完成: $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"
